package txlbs

import (
	"github.com/imroc/req/v2"
	"time"
)

const matrixRequestUri = "https://desc.map.qq.com/ws/distance/v1/matrix"

/*
*
driving：驾车
walking：步行
bicycling：自行车
*/
const matrixCalculatorMode = "walking"

type GetDistanceReq struct {
	From string
	To   string
	Key  string
}

type GetDistanceResp struct {
	Status  int                   `json:"status"`
	Message string                `json:"message"`
	Result  GetDistanceResultResp `json:"result"`
}

// return first point distance, and the unit is m
func (result *GetDistanceResp) FirstDistance() int {
	if len(result.Result.Rows) > 0 {
		row := result.Result.Rows[0]
		if len(row.Elements) > 0 {
			ele := row.Elements[0]
			return ele.Distance
		}
	}
	return 0
}

type GetDistanceResultResp struct {
	Rows []GetDistanceResultRowResp `json:"rows"`
}
type GetDistanceResultRowResp struct {
	Elements []GetDistanceResultElementResp `json:"elements"`
}
type GetDistanceResultElementResp struct {
	Distance int     `json:"distance"`
	Duration float64 `json:"duration"`
}

func GetDistance(disReq GetDistanceReq) (*GetDistanceResp, error) {
	client := req.C().SetTimeout(5 * time.Second).DevMode()
	var result GetDistanceResp
	_, err := client.R().SetQueryParams(map[string]string{
		"mode":   matrixCalculatorMode,
		"from":   disReq.From,
		"to":     disReq.To,
		"output": "JSON",
		"key":    disReq.Key,
	}).SetResult(&result).Get(matrixRequestUri)
	if err != nil {
		return nil, err
	}
	//fmt.Println(resp)
	return &result, nil
}
